<?php 


class EntryKeyWords {
	
	
	private $entrykeywords;

	
    public function getCleanCode($code){
    
        $tags = '/<(.*?)>/';
        $charsout = '[';
        for($i=33 ; $i<255 ; $i++){
            if(($i > 191 && $i < 198) OR ($i > 223 && $i < 230)){
                $code = str_replace(chr($i), chr(97), $code);
            }else if(($i > 199 && $i < 204) OR ($i > 231 && $i < 236)){
                $code = str_replace(chr($i), chr(101), $code);
            }else if(($i > 203 && $i < 208) OR ($i > 235 && $i < 240)){
                $code = str_replace(chr($i), chr(105), $code);
            }else if(($i > 209 && $i < 215) OR ($i > 241 && $i < 247)){
                $code = str_replace(chr($i), chr(111), $code);
            }else if(($i > 216 && $i < 221) OR ($i > 248 && $i < 253)){
                $code = str_replace(chr($i), chr(117), $code);
            }else if($i < 65 OR $i > 122 OR ($i > 90 && $i < 97)){
                $charsout.= '\\'.chr($i);
            }
        }
        $charsout.= ']';
        $cleancode = strtolower($code);
        $cleancode = str_replace(array('-', '_',',','.',';',':'), ' ', $cleancode);
        $cleancode = preg_replace($tags, '', $cleancode);
        $cleancode = preg_replace('/'.$charsout.'/', '', $cleancode);
        $cleancode = str_replace(array('  ', '   ', '    '), ' ', $cleancode);
    
        return $cleancode;
    }

    

    public function getKeyWords($content, $labels, $entrytitle, $head, $langid){
    
        $url = $this->toIso($entrytitle['url']);
        $title = $this->toIso($entrytitle['title']);
        
        if(!empty($head['metadescription'])){ 
        	$metadescription = $this->toIso($head['metadescription']);
        }
        if(!empty($head['metakeywords'])){
        	$metakeywords = $this->toIso($head['metakeywords']);
        }
        if(!empty($content)){
        	$content = $this->toIso($content);
        }
        if($labels){
            foreach($labels as $key=>$label){
                $labels[$key] = $this->toIso($label);
            }
        }
    
        $cleancontent = $this->getCleanCode($content);
        $cleantitle = $this->getCleanCode($title);
        if(!empty($metakeywords)){
        	$cleanmetakeywords = $this->getCleanCode($metakeywords);
        }
        if(!empty($metadescription)){ 
        	$cleanmetadescription = $this->getCleanCode($metadescription);
        }
        if(!empty($labels)){
        	 $cleanlabels = $this->getCleanCode(implode(' ', $labels));
        }
    
        $points = array();
        if(!empty($cleanlabels)){
            $points = $this->addPoints($points, $cleanlabels, $langid, 1, 0.5);
        }
        $points = $this->addPoints($points, $cleantitle, 1, 0.5);
        if(!empty($cleanmetakeywords)){
            $points = $this->addPoints($points, $cleanmetakeywords, 0, 0.25);
        }
        if(!empty($cleanmetadescription)){
            $points = $this->addPoints($points, $cleanmetadescription, 0, 0.25);
        }
        if(!empty($cleancontent)){
            $wordsdensity = $this->wordsDensity($cleancontent, 5);
        }
        if(!empty($labels)){
            $labelsdensity = $this->labelsDensity($cleancode, $labels);
        }
        $points = $this->concatDensity($points, $wordsdensity, 0);
        $points = $this->concatDensity($points, $labelsdensity, 0);
    
        $this->entrykeywords = $points;
    }
    
    
	public function saveKeyWords($entryid, $langid){
	
	    global $DB;
	
	    if ($this->entrykeywords) {
	    	
	      foreach ($this->entrykeywords as $word => $density) {
	      	
	      	unset($keyword);
	      	unset($entrykeyword);
	      	
	        $sql = "SELECT id FROM keywords WHERE langid = ? AND word = ?";
	        $keywordid = $DB->selectResponse($sql, array($langid, $keyword));

	        if (!$keywordid) {

	        	$keyword = new KeyWord();
	        	$keyword->dbobj->word = iconv("UTF-8", "ISO-8859-1", $word);
	        	$keyword->dbobj->langid = $langid;
	        	$keyword->dbobj->timeadded = time();

	        	// We save key
	        	$keywordid->id = $keyword->insert();
	        }

	        // Insert relation entry-keyword
	        $entrykeyword = new EntryKeyWord();
	        $entrykeyword->dbobj->entryid = $entryid;
	        $entrykeyword->dbobj->keywordid = $keywordid->id;
	        $entrykeyword->dbobj->density = $density;
	        $entrykeyword->dbobj->timeadded = time();
	        
	        $entrykeyword->insert();
	        
	      }
	    } 
	}
	
	
	
	
	public function addPoints($array, $string, $langid, $emptypoints=0, $issetpoints=0){
	
	    if(!empty($string) && ($emptypoints != 0 OR $issetpoints != 0)){
	        $keys = explode(' ', $string);
	        foreach($keys as $key){
	          if($this->filterCommonWords($key, $langid) && !is_numeric($key) && $key != ''){
	            if(empty($array[$key]) && $emptypoints != 0){
	                $array[$key] = floatval($emptypoints);
	            }else if(!empty($array[$key]) && $issetpoints != 0){
	                $array[$key] = $array[$key] + floatval($issetpoints);
	            }
	          }
	        }
	    }
	
	    if(empty($array)){ return false;}
	
	    return $array;
	}
	
	
	public function labelsDensity($cleancode, $labels){
	    $nwords = count(explode(' ', $cleancode));
	    $keys = array();
	    foreach($labels as $label){
	        $nlabel = $this->searchWord($cleancode, $label);
	        if($nlabel != 0){
	            $array[$label] = $nlabel;
	        }
	    }
	
	    if (!empty($array)) {
	       $keys = $this->calculateDensity($array, $nwords, count($labels));
	       return $keys;
	    } else {
	        return false;
	    }
	}
	
	
	public function wordsDensity($cleancode, $wordsnumber=5){
	
	    $wordpatron = '[a-z]';
	
	    $array = array();
	    $keys = array();
	
	    $words = explode(' ', $cleancode); 
	    $n = count($words);
	    for($i=0 ; $i<$n ; $i++){
	        if(empty($array[$words[$i]])){
	             $array[$words[$i]] = 1;
	        }else{
	            $array[$words[$i]] = $array[$words[$i]] + 1;
	        }
	    }
	    arsort($array);
	
	    $keys = $this->calculateDensity($array, $n, $wordsnumber);
	
	    return $keys;
	}
	
	
	public function filterCommonWords($word, $langid){
	
	    global $DB;
	
	    $sql = "SELECT id, timesrepeated FROM commonwords WHERE word = ?";
	    $commonword = $DB->selectResponse($sql, array($word));
	
	    if ($commonword) {
	
	        $repeats = intval($commonword->timesrepeated) + 1;
	
	        $updatesql = "UPDATE commonwords SET timesrepeated = ? WHERE id = ?";
	        $DB->executeSql($updatesql, array($repeats, $commonword->id));
	
	        return false;
	    }
	
	    return true;
	}
	
	
	public function searchWord($cleancode, $word){
	
	    $texts = explode(' ', $cleancode);
	    $n = 0;
	    if($texts){
	      foreach($texts as $text){
	        if($text == $word){ $n = $n + 1;}
	      }
	    }
	
	    return $n;
	}
	
	
	public function calculateDensity($keywords, $textwords, $numberofwords){
	    $i = 0;
	    while($i<$numberofwords){
	        $keys[key($keywords)] = round(current($keywords)/$textwords, 2);
	        $i++;
	        next($keywords);
	    }
	
	    return $keys;
	}
	
	
	public function concatDensity($array1, $array2, $newkeys){
	    if(!empty($array1) && !empty($array2)){
	        foreach($array1 as $key1=>$value1){
	            unset($find);
	            foreach($array2 as $key2=>$value2){
	                if($key1 == $key2){
	                    $array[$key1] = $value1 + $value2;
	                    unset($array2[$key2]);
	                    $find = 1;
	                }
	            }
	            if(empty($find)){
	                $array[$key1] = $value1;
	            }
	        }
	        if(!empty($array2) && $newkeys == 1){
	            foreach($array2 as $key=>$value){
	                $array[$key] = $value;
	            }
	        }
	        arsort($array);
	    }else if(empty($array1)){
	        arsort($array2);
	        return array2;
	    }else if(empty($array2)){
	        arsort($array1);
	        return $array1;
	    }else{
	        return false;
	    }
	
	    arsort($array);
	    return $array;
	}
	
	
	public function toUtf($string){
	    return iconv("ISO-8859-1", "UTF-8", $string);
	}
	
	
	public function toIso($string){
	    return iconv("UTF-8", "ISO-8859-1", $string);
	}
	
}

?>